package com.qdaily.ui.data.DataBase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    private static DBHelper dbHelper;

    private int openedConnections = 0;

    private static final int DBVersion = 9;

    public synchronized SQLiteDatabase getReadableDatabase() {
        openedConnections++;
        return super.getReadableDatabase();
    }

    public synchronized SQLiteDatabase getWritableDatabase() {
        openedConnections++;
        return super.getWritableDatabase();
    }

    public synchronized void close() {
        openedConnections--;
        if (openedConnections == 0) {
            super.close();
        }
    }

    public static DBHelper dbHelper() {
        return dbHelper;
    }

    public static void init(Context context) {
        if (dbHelper == null) {
            dbHelper = new DBHelper(context);
        }
    }

    private DBHelper(Context context) {
        super(context, "qdaily.db", null, DBVersion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String praiseHistory2 = "create table praiseHistory2" +
                "(id integer primary key," +
                "server_id integer,"+ // id=文章id || 问卷id || 评论id
                "genre integer," + //genre = 1（赞） || 2（取消赞）
                "praise_type varchar(255)" + //praise_type= article || paper || comment
                ");";
        String readHistory2 = "create table readHistory2" +  //阅读历史
                "(id integer primary key," +
                "server_id integer,"+ // id=文章id || 问卷id || mob id
                "type varchar(255)" + //praise_type= article || paper || mob
                ");";

        db.execSQL(praiseHistory2);
        db.execSQL(readHistory2);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF exists praiseHistory2;");
        db.execSQL("DROP TABLE IF exists readHistory2;");
        onCreate(db);
    }

}
